package com.tsq.security.auth.base;

import com.tsq.security.auth.service.UserServiceDetailImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Map;

/**
 * 短信授权
 *
 * @author Tango
 * @since 2020/9/1
 */

public class SmsTokenGranter extends PasswordFreeGranter {

    private static final String GRANT_TYPE = "sms";
    private static final String REDIS_PREFIX = "user:token:sms:";


    private UserServiceDetailImpl userDetailsService;

    public SmsTokenGranter(UserDetailsService userDetailsService,
                           AuthorizationServerTokenServices tokenServices,
                           ClientDetailsService clientDetailsService,
                           OAuth2RequestFactory requestFactory) {
        super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.userDetailsService = (UserServiceDetailImpl) userDetailsService;
    }

    @Override
    public Authentication parameterGrant(Map<String, String> parameters) {
        String username = parameters.get("username"),
                sms = parameters.get("sms");
        //redis验证
        if (StringUtils.isNoneBlank(username, sms)) {
            String storedSms = (String) userDetailsService.getRedisTemplate().opsForValue().get(REDIS_PREFIX + username);
            if (sms.equals(storedSms)) {
                UserDetails userDetails = getUser(username);
                return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            }else{
                return fail("验证码错误: " + username + ", " + sms);
            }
        }else{
            return fail("参数错误: " + username + ", " + sms);
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    protected UserServiceDetailImpl getUserDetailsServiceBean() {
        return userDetailsService;
    }

}
